/**
 * Title:
 * Description:
 * @author jjtEatJava
 * @date 2017年7月30日
 */
package leap.tools.builder;

import java.io.File;
import java.io.IOException;

import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.MalformedTemplateNameException;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import freemarker.template.TemplateNotFoundException;

/**
 * Title:
 * Description:
 * @author jjtEatJava
 * @date 2017年7月30日
 */
public class FreeMarkService {
	private static Configuration cfg  = null;
	
	public static Configuration getCfg() throws IOException {
		if(cfg==null) {
			init();
		}
		return cfg;
	}

	private static void init() throws IOException {
		// Create your Configuration instance, and specify if up to what FreeMarker
		// version (here 2.3.22) do you want to apply the fixes that are not 100%
		// backward-compatible. See the Configuration JavaDoc for details.
		cfg = new Configuration(Configuration.VERSION_2_3_23);

		// Specify the source where the template files come from. Here I set a
		// plain directory for it, but non-file-system sources are possible too:
		cfg.setDirectoryForTemplateLoading(new File(ClassLoader.getSystemResource("").getPath(), "templates"));

		// Set the preferred charset template files are stored in. UTF-8 is
		// a good choice in most applications:
		cfg.setDefaultEncoding("UTF-8");

		// Sets how errors will appear.
		// During web page *development* TemplateExceptionHandler.HTML_DEBUG_HANDLER is better.
		cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
	}
	
	public static Template getTemplate(String name) throws TemplateNotFoundException, MalformedTemplateNameException, ParseException, IOException {
		return getCfg().getTemplate(name);
	};
}
